namespace Antivirus.Domain.DataLayer.Repositories
{
    using System.Collections.Generic;
    using System.IO;
    using System.Xml.Linq;
    using Digest;
    using Extensions;

    public class XmlFileVirusSignatureRepository : IVirusSignatureRepository
    {
        private const string VirusSignatureNodeName = "VirusSignature";
        private const string NameNodeName = "Name";
        private const string SignatureNodeName = "Signature";

        private readonly string _filename;

        public XmlFileVirusSignatureRepository(string filename)
        {
            _filename = filename;
        }

        public IEnumerable<VirusSignature> GetAllVirusSignatures()
        {
            var xDocument = XDocument.Load(File.OpenRead(_filename));
            var virusSignatureNodes = xDocument.Descendants(VirusSignatureNodeName);

            foreach (var node in virusSignatureNodes)
            {
                var nameNode = node.Element(NameNodeName);
                var nameValue = nameNode.Value;

                var signatureNode = node.Element(SignatureNodeName);
                var signatureValue = signatureNode.Value;

                var hash = new Md5Hash(signatureValue.AsHexString());
                yield return new VirusSignature(nameValue, hash);
            }
        }
    }
}